﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Facebook.Web;
using Facebook.Web.FbmlControls;
using WhsFacebook.Whs;

namespace WhsFacebook.Net.Web.Facebook
{
    public partial class Friends : CanvasFBMLBasePage
    {
        public Friends()
        {
            this.RequireLogin = true;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            using (var db = new Database.WhsFacebookEntities())
            {
                // query instance id
                var defMaster = (DefaultMaster)this.Master;
                var userId = defMaster.FacebookVisit.UserId;
                var friends = defMaster.FacebookVisit.FriendsUserIds.Union(new[] { userId });

                var instanceId = (
                    from t in db.FacebookInstanceMappings
                    where t.FacebookUserId == userId
                    select t.InstanceId
                    ).First();

                // query friends
                var friendsStorage = (
                    from f in db.FacebookUserStorageInfos
                    where friends.Contains(f.FacebookUserId)
                    orderby f.StorageSize descending 
                    select f
                    ).Take(10).ToArray();

                if (friendsStorage.Length <= 0)
                {
                    this.friendsWallContainer.InnerText = "None of your friends is using Windows Home Server on Facebook.";
                }
                else
                {
                    // prepare wall
                    var friendsWall = new HtmlGenericControl("fb:wall");

                    this.friendsWallContainer.Controls.Add(friendsWall);

                    // add friends
                    var pos = 0;

                    foreach (var fs in friendsStorage)
                    {
                        var p = new HtmlGenericControl("fb:wallpost")
                        {
                            InnerHtml = string.Format(
                                "#{3} - <b>{2} total</b> ({0} used, {1} free)",
                                WhsFacebookHelpers.GetNiceFileSize(fs.StorageUsedSpace),
                                WhsFacebookHelpers.GetNiceFileSize(fs.StorageFreeSpace),
                                WhsFacebookHelpers.GetNiceFileSize(fs.StorageSize),
                                ++pos
                                )
                        };

                        p.Attributes.Add("uid", fs.FacebookUserId.ToString());

                        friendsWall.Controls.Add(p);
                    }
                }
            }
        }
    }
}